﻿
using System;
using System.Collections.Generic;
using System.Text;
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace BConsulService
{
    public static class ConsulServiceCollectionExtensions
    {
        //public static IServiceCollection AddConsulService(this IServiceCollection services, IConfiguration configuration)
        //{
        //    //services.AddHttpClient();

        //    //services.AddSingleton<IEurekaService, EurekaService>();
           

        //    return services;
        //}
        public static IApplicationBuilder UseConsulService(this IApplicationBuilder app, IApplicationLifetime lifetime, IOptions<ConsulService> consulService)
        {
            // 添加健康检查路由地址
            app.Map("/health", HealthMap);

 
            var consulClient = new ConsulClient(x => x.Address = new Uri($"{consulService.Value.ServiceUrl}"));//请求注册的 Consul 地址
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                //HTTP = $"https://{healthService.Value.IP}:{healthService.Value.Port}/health",//健康检查地址
                HTTP = $"https://{consulService.Value.IP}:{consulService.Value.Port}/health",//健康检查地址
                Timeout = TimeSpan.FromSeconds(5)
            };

            // Register service with consul
            var registration = new AgentServiceRegistration()
            {
                Checks = new[] { httpCheck },
                ID = consulService.Value.Name + "_" + consulService.Value.Port,
                Name = consulService.Value.Name,
                Address = consulService.Value.IP,
                Port = consulService.Value.Port,
                Tags = new[] { $"服务名称-/{consulService.Value.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签，以便 Fabio 识别
            };

            consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册，内部实现其实就是使用 Consul API 进行注册（HttpClient发起）
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
            });


            return app;
        }



        public static void HealthMap(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                //context.Request
                await context.Response.WriteAsync("OK");
            });
        }
    }
}
